async function changeStatus(userid) {
  const state_id = await new Promise(resolve => {
    wx.showActionSheet({
      itemList: ['禁用', '启用'],
      success: (r) => resolve(r.tapIndex),
      fail: () => resolve(-1)
    })
  })
  if (state_id < 0) return;
  const res = await new Promise(resolve => {
    wx.cloud.callFunction({
      name: 'db_user',
      data: {
        funcName: 'update',
        userid: userid,
        updData: { user_state: state_id }
      },
      success: (r) => resolve(r.result),
      fail: () => resolve()
    });
  })
  if (!res) return;
  wx.showToast({
    title: `已更新 ${res.stats.updated} 条记录，请下拉刷新`,
    icon: 'none',
  })
}

async function changeRole(userid) {
  const role_id = await new Promise(resolve => {
    wx.showActionSheet({
      itemList: ['球场财务管理员', '球场工作人员', '用户'],
      success: (r) => resolve(r.tapIndex),
      fail: () => resolve(-1)
    })
  })
  if (role_id < 0) return;
  const res = await new Promise(resolve => {
    wx.cloud.callFunction({
      name: 'db_user',
      data: {
        funcName: 'update',
        userid: userid,
        updData: { role_id: role_id + 1 }
      },
      success: (r) => resolve(r.result),
      fail: () => resolve()
    });
  })
  if (!res) return;
  wx.showToast({
    title: `已更新 ${res.stats.updated} 条记录，请下拉刷新`,
    icon: 'none',
  })
}

async function search(searchText, searchData) {
  console.log('搜索字段：' + searchText);
  searchText = searchText.trim();
  const resList = await new Promise(resolve => {
    wx.cloud.callFunction({
      name: 'db_user',
      data: {
        funcName: 'query',
        searchText: searchText,
        searchData: searchData
      },
      success: (r) => resolve(r.result),
    });
  })
  return resList.map(o => {
    o.created_time = new Date(o.created_time).Format('yyyy-MM-dd hh:mm:ss');
    o.login_time = o.login_time ? new Date(o.login_time).Format('yyyy-MM-dd hh:mm:ss') : '未知';
    o.gender = ['未知', '男', '女'][o.gender];
    o.user_state = ['已禁用', '已启用'][o.user_state];
    return o;
  })
}

module.exports = {
  title: 'username',
  subtitle: 'user_state',
  data_keys: [
    { k: '_id', v: 'ID' },
    { k: 'real_name', v: '姓名' },
    { k: 'gender', v: '性别' },
    { k: 'phone', v: '手机号' },
    { k: 'role_name', v: '权限' },
    { k: 'created_time', v: '注册时间' },
    { k: 'login_time', v: '上次登录时间' }
  ],
  data_btns: [
    { label: '修改权限', funcName: 'changeRole' },
    { label: '启用/禁用', funcName: 'changeStatus' }
  ],
  search_placeholder: '搜索用户名，真实姓名',
  header_btn: { text: '导出用户数据', url: '/pages/templates/404?errMsg=暂未实现' },
  tabs: [
    { label: '全部', searchData: {} },
    { label: '已启用', searchData: { user_state: 1 } },
    { label: '已禁用', searchData: { user_state: 0 } },
  ],
  changeRole,
  changeStatus,
  search,
}